package cn.zcf.system.service.impl;

import cn.zcf.basic.utils.PageList;
import cn.zcf.system.domain.Role;
import cn.zcf.system.mapper.RoleMapper;
import cn.zcf.system.query.RoleQuery;
import cn.zcf.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper mapper;
    @Override
    public List<Role> loadAll() {
        return mapper.loadAll();
    }

    @Override
    public Role loadById(Long id) {
        return mapper.loadById(id);
    }



    @Override
    public PageList<Role> pageQuery(RoleQuery query) {
        return new PageList<Role>(mapper.queryCount(query),mapper.queryData(query));
    }

    @Override
    public void delete(Long id) {
        //删除中间表：t_role_permission
        mapper.removeRolePermissionByRoldId(id);
        //删除中间表：t_role_menu
        mapper.removeRoleMenuByRoldId(id);
        //删除角色
        mapper.delete(id);
    }

    @Override
    public void update(Role role) {
        mapper.update(role);
        //删除中间表信息：t_role_permission
        mapper.removeRolePermissionByRoldId(role.getId());
        //删除中间表信息：t_role_menu
        mapper.removeRoleMenuByRoldId(role.getId());
        initRelationTable(role);
    }

    @Override
    public void save(Role role) {
        //保存角色信息
        mapper.save(role);
        //操作相关信息：中间表信息
        initRelationTable(role);
    }
    private void initRelationTable(Role role) {
        Long roleId = role.getId();
        //角色分配权限
        List<Long> permissions = role.getPermissions();
        if(permissions.size() > 0){
            mapper.saveRolePermissons(roleId, permissions);
        }

        //角色分配菜单
        List<Long> menus = role.getMenus();
        if(menus.size() > 0) {
            mapper.saveRoleMenus(roleId, menus);
        }
    }
}
